<template>
  <q-page padding class="table-report-page">
      <q-toolbar class="fixed-top">
      <q-toolbar-title>
        资源总览
      </q-toolbar-title>
      <q-space />
    
    <!-- 添加搜索框和导航按钮 -->
    <div class="row items-center q-gutter-x-sm">
        <q-select
          v-model="searchText"
          :options="searchResults"
          @filter="onSearch"
          @update:model-value="onSearchSelect"
          @click="onDropdownClick"
          use-input
          hide-selected
          fill-input
          input-debounce="0"
          style="width: 200px"
          label="搜索"
        >
          <template v-slot:option="{ itemProps, itemEvents, opt }">
            <q-item v-bind="itemProps" v-on="itemEvents">
              <q-item-section>
                <q-item-label>{{ opt.text }} ({{ opt.tableName }})</q-item-label>
              </q-item-section>
            </q-item>
          </template>
        </q-select>
        <q-btn icon="navigate_before" @click="navigateToPrev" :disable="!hasPrev" dense flat />
        <q-btn icon="navigate_next" @click="navigateToNext" :disable="!hasNext" dense flat />
      </div>
      
    <q-btn-toggle
      v-model="currentKey"
      toggle-color="primary"
      :options="tableKeys"
      @update:model-value = "onChangeTable"
    />
    <q-btn label="Download" @click="onDownload" color="primary" />
  </q-toolbar>

    <q-table
      class="my-sticky-header-table"
      color="secondary"
      :loading="loading"
      :rows="rows"
      v-model:pagination="pagination"
      @update:pagination="onPaginationChange"
      :separator="separator"
      :columns="columns"
      :options="[
        { label: 'Horizontal (default)', value: 'horizontal' },
        { label: 'Vertical', value: 'vertical' },
        { label: 'Cell', value: 'cell' },
        { label: 'None', value: 'none' },
      ]"
    >
    <template v-slot:pagination="scope">
        <q-btn
          v-if="scope.pagesNumber > 2"
          icon="first_page"
          color="grey-8"
          round
          dense
          flat
          :disable="scope.isFirstPage"
          @click="scope.firstPage"
        />

        <q-btn
          icon="chevron_left"
          color="grey-8"
          round
          dense
          flat
          :disable="scope.isFirstPage"
          @click="scope.prevPage"
        />

        <q-btn
          icon="chevron_right"
          color="grey-8"
          round
          dense
          flat
          :disable="scope.isLastPage"
          @click="scope.nextPage"
        />

        <q-btn
          v-if="scope.pagesNumber > 2"
          icon="last_page"
          color="grey-8"
          round
          dense
          flat
          :disable="scope.isLastPage"
          @click="scope.lastPage"
        />
      </template>
    </q-table>

      <q-btn label="Back" @click="onBack" color="primary" />
  </q-page>
</template>

<script>
import { ref } from 'vue';
import { exportRawToExcel, exportToExcel } from '../js/api';
import { StoreModel } from '../js/model';

export default {
  setup(){
    return {
      separator: 'vertical',
      pagination: ref({
        sortBy: 'desc',
        descending: false,
        rowsPerPage: 20,  
        page:1
        // rowsNumber: xx if getting data from a server
      }),
    }
  },
  data() {
    return {
      loading : true,
      tableList:{},
      filePath:"",
      rows:[],
      columns:[],
      currentKey:"",
      tableKeys:[],
      chapter:"",

       // ... 原有的 data 属性 ...
      searchText: '',
      searchResults: [],
      currentSearchResults: [],
      currentSearchIndex: -1,
      
    };
  },
  computed: {
    hasPrev() {
      return this.currentSearchResults.length > 0 && this.currentSearchIndex > 0;
    },
    hasNext() {
      return this.currentSearchResults.length > 0 && this.currentSearchIndex < this.currentSearchResults.length - 1;
    }
  },

  async mounted(){

    this.chapter = StoreModel["chapter"]
    let res = await exportToExcel({chapter:this.chapter})
    StoreModel["TableReport"] = res;
    let tables = StoreModel["TableReport"].data.data.data
    this.tableList = tables
    this.filePath = StoreModel["TableReport"].data.data.filePath

    

    this.tableKeys = Object.keys(this.tableList).map((item)=>{
      return {label: item, value: item}
    })

    this.currentKey = Object.keys(this.tableList)[0]
    this.loadTable();
    this.loading = false

  },  
  created(arg){
    console.log("created",StoreModel["TableReport"])
    // let tables = StoreModel["TableReport"].data.data.data
    
    // this.tableList = tables
    // this.filePath = StoreModel["TableReport"].data.data.filePath

  },
  updated(){

  },
  methods: {
    onPaginationChange(newPagination) {
      // console.log('pagination changed', newPagination);
      this.pagination = newPagination;
    },

    navigateToResult(result) {
      if (!result) return;
      
      this.currentKey = result.tableName;
      this.loadTable();
      
      this.$nextTick(async () => {
         // 计算目标行应该在哪一页
         const targetPage = Math.floor(result.rowIndex / this.pagination.rowsPerPage) + 1;
        
        // 设置页码
        // 更新分页
        
        // 更新分页
        this.onPaginationChange({
          ...this.pagination,
          page: targetPage
        });


        await this.$nextTick();

        // 获取表格的所有行
        const rows = document.querySelector('.q-table tbody').querySelectorAll('tr');
        // 计算在当前页面中的相对行索引
        const relativeIndex = result.rowIndex % this.pagination.rowsPerPage;


        if (rows[relativeIndex]) {
          // 确保表格可见
          rows[relativeIndex].scrollIntoView({ behavior: 'smooth', block: 'center' });
          rows[relativeIndex].classList.add('highlighted-row');
          setTimeout(() => {
            rows[relativeIndex].classList.remove('highlighted-row');
          }, 2000);
        }
      });
    },

    navigateToNext() {
      if (this.hasNext) {
        this.currentSearchIndex++;
        const nextResult = this.currentSearchResults[this.currentSearchIndex];
        this.searchText = this.searchInputText; // 保持搜索文本不变
        this.navigateToResult(nextResult);
      }
    },

    navigateToPrev() {
      if (this.hasPrev) {
        this.currentSearchIndex--;
        const prevResult = this.currentSearchResults[this.currentSearchIndex];
        this.searchText = this.searchInputText; // 保持搜索文本不变
        this.navigateToResult(prevResult);
      }
    },
    
    onSearch(val, update) {
      this.searchInputText = val;

      update(() => {
        const results = [];
        Object.entries(this.tableList).forEach(([tableName, tableData]) => {
          tableData.forEach((row, rowIndex) => {
            if (!val) return;
            
            const matchFound = Object.values(row).some(value => 
              String(value).toLowerCase().includes(val.toLowerCase())
            );
            if (matchFound) {
              results.push({
                text: Object.values(row).filter(v => v !== null && v !== undefined).join(' - '), // 过滤空值
                tableName,
                rowIndex,
                row,
                searchText: val
              });
            }
          });
        });
        this.searchResults = results;
        this.currentSearchResults = results;
        this.currentSearchIndex = -1;
      });
    },

    onSearchSelect(value) {
      if (value) {
        this.searchText = this.searchInputText;
        // 设置当前索引为选中项的索引
        this.currentSearchIndex = this.currentSearchResults.findIndex(
          item => item.text === value.text && item.tableName === value.tableName
        );
        this.navigateToResult(value);
      }
    },
    onDropdownClick() {
      // 如果已经有搜索文本，直接使用它进行搜索
      if (this.searchText) {
        this.onSearch(this.searchText, (update) => {
          update();
        });
        return;
      }
      
      // 如果没有搜索文本，显示空结果
      this.searchResults = [];
      this.currentSearchResults = [];
      this.currentSearchIndex = -1;
    },
    onChangeTable(){
      this.loadTable()
    },
    async onDownload(){
      let res = await exportToExcel({chapter:this.chapter});
      this.filePath = res.data.data.filePath;
      window.location.href = `${process.env.DONWLOAD_ROOT}/${this.filePath}`;
    },

    // async onDownloadRaw(){
    //   let res = await exportRawToExcel({chapter:this.chapter})
    //   let rawFilePath = res.data.data.filePath;
    //   window.location.href = `${process.env.DONWLOAD_ROOT}/${rawFilePath}`;
    // },    

    loadTable(){
      let data = this.tableList[this.currentKey]

      this.columns = Object.keys(data[0]).map((item)=>{
         
        return { name: item, label: item, field: item, align: 'left' }   
      })

      this.rows = data;

      // 切换表格时重置分页到第一页
      this.onPaginationChange({
        ...this.pagination,
        page: 1
      });
    },
    async onBack() {
      this.$router.back()
    }
  }
};
</script>

<style lang="scss">
.table-report-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding-top: 50px !important; // 为固定工具栏留出空间
}

.fixed-top {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background: white; // 或者与你的主题匹配的颜色
  padding: 0 16px;
}

.toggle-container {
  position: sticky;
  top: 50px; // 工具栏高度
  z-index: 99;
  background: white; // 或者与你的主题匹配的颜色
  padding: 8px 0;
}

.table-container {
  flex: 1;
  overflow: hidden;
  position: relative;
  
  .my-sticky-header-table {
    height: calc(100vh - 120px); // 减去工具栏和toggle的高度
    
    .q-table__middle {
      max-height: 100%;
      overflow: auto;
    }
    
    thead tr th {
      position: sticky;
      z-index: 1;
    }
    
    /* 防止表头阴影被裁切 */
    thead tr:last-child th {
      top: 0;
    }
  }
}


.q-table {
  .q-pagination {
    .q-btn {
      color: #424242; // 深灰色按钮文字
      background: #f5f5f5; // 浅灰色背景
      
      &.q-btn--active {
        background-color: #1976d2; // primary 颜色
        color: white;
      }
      
      &:hover:not(.q-btn--active) {
        background-color: #e0e0e0;
      }
    }
  }
}

// 如果需要调整按钮间距
.q-pagination {
  .q-btn {
    margin: 0 2px; // 调整按钮间距
  }
}

.highlighted-row {
  background-color: rgba(25, 118, 210, 0.1);
  transition: background-color 0.5s ease;
}
</style>